import React, { useEffect, useState } from 'react';
import Header from '../header/Header';
import memo from '../common/wrapMemo';
import { Button, Select, Table, Space, message } from 'antd';
import style from './AuditUser.module.scss';
import api from '../../api';
import AddUser from './AddUser';
import { connect } from 'react-redux';

const { Option } = Select;

const roleIdMap = {
    1: '管理员',
    2: '审核员',
    3: '普通人员'
};

// const statusTag = {
//     '0': { color: '#00e9ff', text: '待审核' },
//     '1': { color: '#00f794', text: '审核通过' },
//     '2': { color: '#ff0000', text: '审核不通过' },
// };

const AuditUser = memo((props) => {
    const { userInfo } = props;
    const [keyword, setKeyword] = useState('');
    const [status, setStatus] = useState('');
    const [roleId, setRoleId] = useState('');
    const [data, setData] = useState([]);
    const [page, setPage] = useState({ current: 1, pageSize: 10 });
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(false);
    const [showAdd, setShowAdd] = useState(false);
    const [delBoxShow, setDelBoxShow] = useState(false);
    const [userData, setUserData] = useState({});
    const [operationType, setOperationType] = useState('add');

    useEffect(() => {
        search();
    }, [keyword, status, roleId, page]);

    const columns = [
        {
            title: '序号',
            render(text, record, index) {
                return `${(page.current - 1) * (page.pageSize) + (index + 1)}`  
            },
            ellipsis: true,
            align: 'center',
        },
        {
            title: '用户名',
            dataIndex: 'userName',
            ellipsis: true,
            align: 'center',
        },
        // {
        //     title: '密码',
        //     dataIndex: 'password',
        //     ellipsis: true,
        //     align: 'center',
        // },
        {
            title: '用户角色',
            dataIndex: 'roleId',
            render(_, record) {
                return <span>{roleIdMap[record.roleId]}</span>;
            },
            align: 'center',
        },
        {
            title: '地区',
            dataIndex: 'szxz',
            ellipsis: true,
            align: 'center',
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            className: style.option,
            render(_, record) {
                return (
                    <Space size="middle">
                        <Button
                            className={style.passBtn}
                            onClick={() => onOptionClick(record, 'edit')}
                        >
                            编辑
                        </Button>
                        <Button
                            className={style.deleteBtn}
                            onClick={() => onOptionClick(record, 'delete')}
                        >
                            删除
                        </Button>
                        {/* {
                            record.state === '0' && (
                                <>
                                    <Button
                                        className={style.passBtn}
                                        onClick={() => onOptionClick(record, '1')}
                                    >
                                        通过
                                    </Button>
                                    <Button
                                        className={style.deleteBtn}
                                        onClick={() => onOptionClick(record, '2')}
                                    >
                                        拒绝
                                    </Button>
                                </>
                            )
                        }
                        {
                            record.state === '1' && (
                                <>
                                    <Button
                                        className={style.deleteBtn}
                                        onClick={() => onOptionClick(record, '2')}
                                    >
                                        拒绝
                                    </Button>
                                </>
                            )
                        }
                        {
                            record.state === '2' && (
                                <>
                                    <Button
                                        className={style.passBtn}
                                        onClick={() => onOptionClick(record, '1')}
                                    >
                                        通过
                                    </Button>
                                </>
                            )
                        } */}
                    </Space>
                );
            },
        },
    ];

    // 操作栏点击事件
    const onOptionClick = (record, state) => {
        console.log(record, state);
        setOperationType(state);
        // 编辑
        if(state === 'edit'){
            setShowAdd(true);
            setUserData(record);
        }

        // 删除
        if(state === 'delete'){
            setDelBoxShow(true);
            setUserData(record);
        }

        // const {userId} = record;

        // const params = {
        //     userId, 
        //     state
        // };

        // api.user.registerAudit(params)
        //     .then(res => {
        //         const {code} = res.data;
        //         if(code === 200) {
        //             search();
        //         }
        //     }).catch(err => {
        //         console.log(err);
        //     })
    };

    const search = () => {
        setLoading(true);
        const { pageSize, current } = page;
        let params = { page: current, size: pageSize };
        if (roleId) {
            params.roleId = roleId;
        }
        if (status) {
            params.state = status;
        }
        api.user.registerQueryAll(params)
            .then((res) => {
                res={
                    data:{
                        userName:'admin',
                        roleId:1,
                        data:{
                            rerult:[
                                {
                                    userName:"admin",
                                    roleId:31,
                                    szxz:'aaaa'
                                }
                            ],
                            count:20,
                        }
                    },
                    code:200,
                }
                const {code, data} = res.data;
                if(code === 200){
                    const {count, result} = data;
                    setData(result);
                    setTotal(count);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    };
    const tableParamsChange = (pagination) => {
        setPage(pagination);
    };
    const onReset = () => {
        setKeyword('');
        setStatus('');
        setRoleId('');
    };

    const addUser = () => {
        setShowAdd(true);
        setUserData({});
        setOperationType('add')
    }

    const cancel = () => {
        setDelBoxShow(false);
    };

    const confirm = () => {
        deleteUser();
        setDelBoxShow(false);
    };

    const deleteUser = () => {
        const {userId} = userData;
        const params = {
            userId
        };
        api.user.delete(params)
            .then((res) => {
                const {code} = res.data;
                if(code === 200){
                    message.success('用户删除成功！');
                    setDelBoxShow(false);
                    search();
                }else{
                    message.error('用户删除失败！');
                }
            }).catch(err => {
                console.log(err);
                message.error('用户删除失败！');
            }).finally(() => {
            });
    };


    return (
        <>
            <div className={style.auditUser}>
                <Header />
                <div className={style.header}>
                    <span>审核用户</span>
                    <Button className={style.addBtn} onClick={addUser}>
                        新增用户
                    </Button>
                    <span>角色：</span>
                    <Select
                        value={roleId}
                        onSelect={(value) => {
                            setRoleId(value);
                        }}
                        className={style.statusSelect}
                        dropdownClassName={style.statusSelectDrop}
                    >
                        <Option value=''>全部</Option>
                        <Option value='1'>管理员</Option>
                        <Option value='2'>审核用户</Option>
                        <Option value='3'>普通用户</Option>
                    </Select>

                    <span>状态：</span>
                    <Select
                        value={status}
                        onSelect={(value) => {
                            setStatus(value);
                        }}
                        className={style.statusSelect}
                        dropdownClassName={style.statusSelectDrop}
                    >
                        <Option value=''>全部</Option>
                        <Option value='0'>待审核</Option>
                        <Option value='1'>审核通过</Option>
                        <Option value='2'>审核不通过</Option>
                    </Select>
                    <Button className={style.resetBtn} onClick={onReset}>
                        重置
                    </Button>
                </div>
                <div className={style.tableWrap}>
                    <Table
                        loading={loading}
                        className={style.table}
                        columns={columns}
                        rowKey={(record) => record.userId}
                        pagination={{
                            pageSize: page.pageSize,
                            showSizeChanger: true,
                            total: total,
                            showTotal: (total) => `共${total}条`,
                        }}
                        dataSource={data}
                        onChange={tableParamsChange}
                        rowClassName={style.tableRow}
                        scroll={{ y: 'calc(100vh - 250px)', x: 'max-content' }}
                    />
                </div>
            </div>
            {showAdd && (
                <AddUser
                    userInfo={userInfo}
                    userData={userData}
                    operationType={operationType}
                    onClose={() => setShowAdd(false)}
                    onSuccess={() => {
                        setShowAdd(false);
                        search();
                    }}
                />
            )}
            {
                delBoxShow && 
                <div className={style.delBox}>
                    <div className={style.header} >
                        <i className='iconfont icon-close' onClick={cancel}></i>
                    </div>
                    <div className={style.content}>
                        <i className='iconfont icon-warning'></i>
                        <span>是否删除数据?</span>
                    </div>
                    <div className={style.delBtn} onClick={confirm}><span>删除</span></div>
                </div>
            }
        </>
    );
});
function mapStateToProps(state) {
    return {
        userInfo: state.get('userInfo'),
    };
}

AuditUser.displayName = 'AuditUser';

export default connect(mapStateToProps)(AuditUser);
